<template>
  <el-dialog :close-on-click-modal='false' title="菜单权限" :visible.sync="dialogFormVisible" :before-close="cancel">
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-row>
        <el-tree :data="treeList" show-checkbox node-key="id" ref="tree" highlight-current :props="defaultProps">
        </el-tree>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <!-- <div @click="setCheckedKeys">获取</div> -->
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      required: false
    },
    api: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogFormVisible: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
      },
      form: {
        roleName: '',
        menu: []
      },
    };
  },
  watch: {
    showDialog: {
      handler (v) {
        this.dialogFormVisible = v
        let routerTree = []
        if (v) {
          this.form = { ...this.form, ...this.formData }
          this.$router.options.routes.forEach(element => {
            if (element.path !== '/' && element.path !== '/404' && element.path !== '/login' && element.path !== '*') {
              routerTree.push(element)
            }
          });
          this.treeList = this.mapRouter(routerTree)
          setTimeout(() => {
            this.setCheckedKeys()
          }, 100)
        }
      }
    }
  },
  methods: {
    getCheckedKeys () {
      console.log(this.$refs.tree.getHalfCheckedKeys())
      console.log(this.$refs.tree.getCheckedKeys());
      let pRouterList = this.$refs.tree.getHalfCheckedKeys()
      let cRouterList = this.$refs.tree.getCheckedKeys()
      this.form.menu = JSON.stringify(pRouterList.concat(cRouterList))
    },
    setCheckedKeys () {
      console.log(this.form.menu)
      if (this.form.menu && typeof this.form.menu === "string") {
        this.$refs.tree.setCheckedKeys(JSON.parse(this.form.menu));
      } else {
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    mapRouter (list) {
      let routerTree = []
      if (list.length > 0) {
        list.forEach(item => {
          routerTree.push({
            id: item.path,
            label: item.meta.title ? item.meta.title : '无菜单名称',
            path: item.path,
            name: item.name,
            children: this.mapRouter(item.children ? item.children : [])
          })
        })
      };
      return routerTree
    },
    //关闭
    close (isRef) {
      this.$emit('closeDialog', isRef)
      this.$refs.form.resetFields()
    },
    //取消
    cancel () {
      this.form = {
        roleName: '',
        menu: []
      }
      this.close()
    },
    //确认
    confirm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.roleSort = 2
          this.form.roleKey = 'common'
          //  this.api 添加编辑接口 （注意传参）
          this.getCheckedKeys()
          this.api(this.form).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.cancel()
              this.close(true)
            } else {
              this.$message({
                type: 'info',
                message: res.msg || '操作失败!'
              });
            }
          })
        } else {
          return false;
        }
      });
    }
  }
};
</script>